package com.candy.sys.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.candy.common.exception.BusinessException;
import com.candy.common.result.R;
import com.candy.sys.service.IAttachmentService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import com.candy.sys.entity.Attachment;
import com.candy.common.controller.BaseController;
import io.swagger.annotations.Api;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 文件 前端控制器
 * </p>
 *
 * @author pxs
 * @since 2021-07-06
 */
@Api(tags="文件")
@RestController
@RequestMapping("/sys/attachment")
public class AttachmentController extends BaseController<IAttachmentService, Attachment> {

	@Value("${candy.file.path:C:/upload/file}")
	private String rootPath;

	@Override
	@ApiOperation(value = "列表")
	@GetMapping("/list")
	public R list(Attachment attachment)
	{
		LambdaQueryChainWrapper<Attachment> attachmentLambdaQueryChainWrapper = baseService.lambdaQuery();
		if(StringUtils.isNotEmpty(attachment.getName()))
		{
			attachmentLambdaQueryChainWrapper.like(Attachment::getName, attachment.getName());
			attachment.setName(null);
		}
		attachmentLambdaQueryChainWrapper.setEntity(attachment);
		IPage<Attachment> pageModel = baseService.page(getPage(), attachmentLambdaQueryChainWrapper.getWrapper());
		return R.success(pageModel);
	}


	/**
	 * 附件上传
	 * @param request
	 * @param attachment
	 * @param files
	 * @return
	 */
	@ApiOperation(value = "附件上传")
	@PostMapping("/upload")
	@Transactional
	public R upload(HttpServletRequest request, Attachment attachment, @RequestParam("files") MultipartFile[] files){
		if(files==null||files.length==0)
		{
			throw  new BusinessException("请选择文件");
		}
		List<String> filePathList = new ArrayList<>();
	 	LocalDateTime nowDateTime = LocalDateTime.now();
		DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
		//创建文件在服务器端存放路径
		String filePath = rootPath+"/"+dateTimeFormatter.format(nowDateTime);
		for (MultipartFile multipartFile : files)
		{
			Attachment perAttachment = new Attachment();
			perAttachment.setRemarks(attachment.getRemarks());
			perAttachment.setName(multipartFile.getOriginalFilename());
			perAttachment.setType(multipartFile.getContentType());
			perAttachment.setSize(multipartFile.getSize());
			perAttachment.setRalationId(attachment.getRalationId());
			if(attachment.getIsAuthorize()!=null)
			{
				perAttachment.setIsAuthorize(attachment.getIsAuthorize());
			}
			perAttachment.setPath(filePath);
			if(baseService.save(perAttachment))
			{
				try
				{
					File file = new File(filePath);
					if (!file.exists())
					{
						file.mkdirs();
					}
					String perFilePath = filePath + File.separator + perAttachment.getId();
					filePathList.add("/sys/attachment/web/"+perAttachment.getId());
					// 保存文件
					multipartFile.transferTo(new File(perFilePath));
				}
				catch (IOException e)
				{
					e.printStackTrace();
				}
			}
			else
			{
				return  R.error(multipartFile.getOriginalFilename());
			}
		}
		JSONObject resultObj = new JSONObject();
		resultObj.put("files",filePathList);
		return R.success(resultObj);
	}

	/**
	 * 附件下载
	 * @param id
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/web/{id}", method = RequestMethod.GET)
	public ResponseEntity<InputStreamResource> web(@PathVariable("id") Long id) throws IOException {
		Attachment attachment = baseService.getById(id);
		if(attachment.getIsAuthorize()==1)
		{
			throw new BusinessException("请登录");
		}
		String filePath = attachment.getPath()+"/"+id;
		FileSystemResource file = new FileSystemResource(filePath);
		HttpHeaders headers = new HttpHeaders();
		headers.add("Cache-Control", "no-cache, no-store, must-revalidate");

		// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
		String fileName = URLEncoder.encode(attachment.getName(), "UTF-8").replaceAll("\\+", "%20");
		headers.add("Content-disposition", "attachment;filename*=utf-8''" + fileName);
		headers.add("Pragma", "no-cache");
		headers.add("Expires", "0");

		return ResponseEntity
				.ok()
				.headers(headers)
				.contentLength(file.contentLength())
				.contentType(MediaType.parseMediaType("application/octet-stream"))
				.body(new InputStreamResource(file.getInputStream()));
	}

	/**
	 * 附件下载
	 * @param id
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/download/{id}", method = RequestMethod.GET)
	public ResponseEntity<InputStreamResource> download(@PathVariable("id") Long id) throws IOException {
		Attachment attachment = baseService.getById(id);
		String filePath = attachment.getPath()+"/"+id;
		FileSystemResource file = new FileSystemResource(filePath);
		HttpHeaders headers = new HttpHeaders();
		headers.add("Cache-Control", "no-cache, no-store, must-revalidate");

		// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
		String fileName = URLEncoder.encode(attachment.getName(), "UTF-8").replaceAll("\\+", "%20");
		headers.add("Content-disposition", "attachment;filename*=utf-8''" + fileName);
		headers.add("Pragma", "no-cache");
		headers.add("Expires", "0");

		return ResponseEntity
				.ok()
				.headers(headers)
				.contentLength(file.contentLength())
				.contentType(MediaType.parseMediaType("application/octet-stream"))
				.body(new InputStreamResource(file.getInputStream()));
	}
}
